//
//  YLUserViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/3/26.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "YLUserViewController.h"
#import "YLUserLoginViewController.h"
#import "YLUserRegisterViewController.h"
#import "YLForgetPasswordViewController.h"
#import "LKUserLoginViewModel.h"
#import "LKSwitchRootVcTool.h"
#import "YLRegisterViewController.h"
//#import "LKUserInfor.h"
#import "LKUserInforTool.h"

@interface YLUserViewController ()

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *leftView;
@property (weak, nonatomic) IBOutlet UIView *rightView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *topTF;
@property (weak, nonatomic) IBOutlet UIButton *phoneBtn;
@property (weak, nonatomic) IBOutlet UITextField *bottomTF;
@property (weak, nonatomic) IBOutlet UIButton *userNameBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;

@property (nonatomic, strong) YLUserLoginViewController *userLoginController;
@property (nonatomic, strong) YLUserRegisterViewController *userRegisterViewController;
@property(nonatomic,strong) LKUserLoginViewModel *viewModel;
@end

@implementation YLUserViewController

-(LKUserLoginViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[LKUserLoginViewModel alloc] init];
    }
    return _viewModel;
}


- (IBAction)login:(UIButton *)sender {
    sender.selected = !sender.selected;
    _leftView.hidden = NO;
    _rightView.hidden = YES;
    _phoneBtn.selected = NO;
    _topTF.placeholder = @"输入用户名";
    [_topTF setText:@""];
    [_bottomTF setText:@""];
    [_topTF resignFirstResponder];
    [_bottomTF resignFirstResponder];

}

- (IBAction)phoneAction:(id)sender {
    UIButton *btn = sender;
    btn.selected = !btn.selected;
    _leftView.hidden = YES;
    _rightView.hidden = NO;
    _userNameBtn.selected = NO;
    _topTF.placeholder = @"输入手机号";
    [_topTF setText:@""];
    [_bottomTF setText:@""];
    [_topTF resignFirstResponder];
    [_bottomTF resignFirstResponder];
    NSLog(@"%lu",_topTF.text.length);
}

- (IBAction)forgetPasswordAction:(id)sender {
    YLForgetPasswordViewController *vc = [[YLForgetPasswordViewController alloc] initWithNibName:@"YLForgetPasswordViewController" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self playOrNotRegis];
    [self setCorder:self.topView];
    [self setCorder:self.bottomView];
    [self setCorder:self.loginBtn];
    [self bindViewModel];
}

/**
 数据信号绑定
 */
-(void)bindViewModel{
    [self.loginBtn setBackgroundImage:[self imageWithColor:blueDefault] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
    RAC(self.loginBtn,enabled) = self.viewModel.enableLoginSignal;
    RAC(self.viewModel,userName) = self.topTF.rac_textSignal;
    RAC(self.viewModel,passWord) = self.bottomTF.rac_textSignal;
}

-(void)setCorder:(UIView *)view{
    view.layer.cornerRadius = ([UIScreen mainScreen].bounds.size.width - 50) * 45 /310 / 2;
    view.layer.masksToBounds = YES;
    if ([view isKindOfClass:[UIButton class]]) {
        return;
    }
    view.layer.borderWidth = 1;
    view.layer.borderColor = COLOR_HEX(0xE0E0E0).CGColor;
}
//颜色转换为图片
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); //宽高 1.0只要有值就够了
    UIGraphicsBeginImageContext(rect.size); //在这个范围内开启一段上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);//在这段上下文中获取到颜色UIColor
    CGContextFillRect(context, rect);//用这个颜色填充这个上下文
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();//从这段上下文中获取Image属性,,,结束
    UIGraphicsEndImageContext();
    
    return image;
}
- (IBAction)loginAction:(id)sender {
    if (self.userNameBtn.selected) {
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_topTF.text,@"UserName",_bottomTF.text,@"Password", nil];
        NSLog(@"%@",param);
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:userLoginUrl parameters:param progress:^(NSProgress * _Nullable progress) {

        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            LKUserInfor *userInfor = [LKUserInfor accountWithDict:responseObject];
            [LKUserInforTool saveAccount:userInfor];
            [LKSwitchRootVcTool switchRootController];
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];

    }else{
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_topTF.text,@"TelCode",_bottomTF.text,@"Password", nil];
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:phoneLoginUrl parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            LKUserInfor *userInfor = [LKUserInfor accountWithDict:responseObject];
            [LKUserInforTool saveAccount:userInfor];
            [LKSwitchRootVcTool switchRootController];
        } failure:^(NSString * _Nullable errorMessage) {
            NSLog(@"%@",errorMessage);
        }];

    }
}

/**
 展示或者不展示注册按钮
 */
-(void)playOrNotRegis{
    NSDictionary *inforDic = [[NSBundle mainBundle] infoDictionary];
      NSString *app_Version = [inforDic objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"版本号：%@",app_Version);
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:registerButtonUrl parameters:nil progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        
        if ([responseObject[@"result"] isEqual:app_Version]) {
            UIButton *regisBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [regisBtn setTitle:@"注册" forState:UIControlStateNormal];
            [regisBtn setTitleColor:blueDefault forState:UIControlStateNormal];
            regisBtn.titleLabel.font = [UIFont systemFontOfSize:12];
            [self.view addSubview:regisBtn];
            [regisBtn addTarget:self action:@selector(gotoRegisterAction:) forControlEvents:UIControlEventTouchUpInside];
            [regisBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.forgetBtn.mas_centerY);
                make.left.equalTo(self.view.mas_left).offset(49);
            }];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];

}
-(void)gotoRegisterAction:(UIButton *)btn{
    YLRegisterViewController *vc = [[YLRegisterViewController alloc] initWithNibName:@"YLRegisterViewController" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
